import * as React from 'react';
import { Button, Input, Switch, Table } from 'antd';
import { ColumnProps } from 'antd/es/table';
import styles from './styles/index.less';

export interface EquTableDataItem {
  id: string;
  ownNet: string;
  dbh: string;
  description: string;
  checked: boolean;
}

export interface EquTableProps {
  dataSource?: EquTableDataItem[];
  onChange?: (data: EquTableDataItem[]) => void;
  onEquSelect?: () => void;
}

export interface EquTableState {
  dataSource: EquTableDataItem[];
}

function shouldUpdateDataSource(data: EquTableDataItem[], data2: EquTableDataItem[]) {
  if (data.length !== data2.length) {
    return true;
  }
  return JSON.stringify(data) !== JSON.stringify(data2);
}

class EquTable extends React.Component<EquTableProps, EquTableState> {
  public static propTypes = {};
  public static defaultProps = {};

  public constructor(props: Readonly<EquTableProps>) {
    super(props);
    const { dataSource = [] } = props;
    this.state = {
      dataSource: this.getDataSource(dataSource),
    };
  }

  public componentDidUpdate(prevProps: Readonly<EquTableProps>) {
    const preDataSource = prevProps.dataSource || [];
    const dataSource = this.props.dataSource || [];
    if (shouldUpdateDataSource(preDataSource, dataSource)) {
      this.setState({ dataSource: this.getDataSource(dataSource) });
    }
  }

  public render() {
    const columns: ColumnProps<EquTableDataItem>[] = [
      {
        title: '所属管网',
        dataIndex: 'ownNet',
      },
      {
        title: '本点号',
        dataIndex: 'dbh',
      },
      {
        title: '位置描述',
        dataIndex: 'description',
        render: (_, record, index) => {
          return (
            <div>
              <Input.TextArea
                value={record.description}
                placeholder="请输入位置描述信息"
                className={styles.desc}
                onChange={({ target: { value } }) => this.handleDescChange(record, index, value)}
              />
            </div>
          );
        },
      },
      {
        title: '操作要求',
        dataIndex: '__rc',
        render: (_, record, index) => {
          return (
            <Switch checked={record.checked} onChange={(checked) => this.handleSwitchChange(record, index, checked)} />
          );
        },
      },
      {
        title: '操作',
        dataIndex: '__action',
        render: (_, record, index) => {
          return (
            <div className={styles.action}>
              <div
                className={styles.actionBtn}
                onClick={(e) => {
                  e.stopPropagation();
                  this.handleDelete(record, index);
                }}
              >
                删除
              </div>
              <div
                className={styles.actionBtn}
                onClick={(e) => {
                  e.stopPropagation();
                  this.handleAdd(record, index);
                }}
              >
                添加
              </div>
              <div
                className={styles.actionBtn}
                onClick={(e) => {
                  e.stopPropagation();
                  this.handleEquSelect(record, index);
                }}
              >
                设备选择
              </div>
            </div>
          );
        },
      },
    ];
    const dataSource = this.state.dataSource || [];
    return (
      <div>
        <div>
          {dataSource.length ? (
            <Table
              className={styles.table}
              pagination={false}
              rowKey={'id'}
              size="middle"
              bordered
              columns={columns}
              dataSource={dataSource || []}
            />
          ) : (
            <Button onClick={() => this.handleAdd(null, 0)}>+添加设备</Button>
          )}
        </div>
      </div>
    );
  }

  private handleEquSelect(_: EquTableDataItem, _index: number) {
    const { onEquSelect } = this.props;
    onEquSelect?.();
  }

  private handleDelete(_record: EquTableDataItem, index: number) {
    const dataSource = [...this.state.dataSource];
    dataSource.splice(index, 1);
    this.setState({ dataSource }, this.triggerChange);
  }

  private handleAdd(_record: EquTableDataItem | null, index: number) {
    const dataSource = [...this.state.dataSource];
    dataSource.splice(index + 1, 0, {
      id: `-${Date.now()}`,
      ownNet: '',
      dbh: '',
      description: '',
      checked: true,
    });
    this.setState({ dataSource }, this.triggerChange);
  }

  private triggerChange() {
    const { onChange } = this.props;
    const { dataSource } = this.state;
    onChange?.(dataSource);
  }

  private getDataSource = (dataSource: EquTableDataItem[] = []) => {
    return dataSource.map((item) => {
      return item;
    });
  };

  private handleSwitchChange(_record: EquTableDataItem, index: number, checked: boolean) {
    this.setState(
      (prevState) => ({
        dataSource: prevState.dataSource.map((v, i) => (i === index ? { ...v, checked } : { ...v })),
      }),
      this.triggerChange
    );
  }

  private handleDescChange(_record: EquTableDataItem, index: number, value: string) {
    this.setState(
      (prevState) => ({
        dataSource: prevState.dataSource.map((v, i) => (i === index ? { ...v, description: value } : { ...v })),
      }),
      this.triggerChange
    );
  }
}

export default EquTable;
